package web;

import com.alibaba.fastjson2.JSONObject;
import core.AjaxResult;
import core.BaseHttpServlet;
import dao.impl.LoginDaoImpl;

import domain.Student;
import service.ILoginService;

import service.impl.LoginServiceImpl;
import service.impl.StudentServiceImpl;
import util.RequestUtils;
import util.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录
 */
@WebServlet("/student/login")
public class LoginServlet extends BaseHttpServlet {

    private ILoginService loginService;

    @Override
    public void init() throws ServletException {
        loginService = new LoginServiceImpl(new LoginDaoImpl());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pathInfo = req.getPathInfo();
        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(1800);
//        switch (pathInfo) {
//            case "/login":
        // 实现登录功能
        JSONObject jsonObject = RequestUtils.getReqJsonBody(req, JSONObject.class);
        // 执行逻辑
        executeBusiness(resp, response -> {
            try {
                Student student = loginService.login(jsonObject.getString("student_id"), jsonObject.getString("student_password"));
                // 登录成功
                // 设置登录用户
                req.getSession().setAttribute("student", student);
                ResponseUtils.responseJSON(resp, AjaxResult.success(student));
            } catch (Exception e) {
                System.out.println(e);
            }
        });
//                break;
//        }

    }

}
